package com.uflo.test.view;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hsqldb.lib.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.hibernate.HibernateDao;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.model.task.Task;
import com.bstek.uflo.model.task.TaskState;
import com.bstek.uflo.query.Query;
import com.bstek.uflo.query.TaskQuery;
import com.bstek.uflo.service.ProcessService;
import com.bstek.uflo.service.StartProcessInfo;
import com.bstek.uflo.service.TaskOpinion;
import com.bstek.uflo.service.TaskService;
import com.uflo.test.model.BaoXiao;
import com.uflo.test.model.BaoxiaoItem;
import com.uflo.test.model.Orderflow;

@Component("baoXiaoMaintain")
public class BaoXiaoMaintain extends HibernateDao {

	@Autowired
	@Qualifier(ProcessService.BEAN_ID)
	private ProcessService propcessService;

	@Autowired
	@Qualifier(TaskService.BEAN_ID)
	private TaskService taskService;

	/**
	 * 加载报销单数据
	 */
	@SuppressWarnings("unchecked")
	@DataProvider
	public BaoXiao loadBaoXiao(String businessId) {
		Session session = getSessionFactory().openSession();

		if (StringUtil.isEmpty(businessId)) {
			return new BaoXiao();
		} else {
			try {
				BaoXiao bx = (BaoXiao) session.get(BaoXiao.class, businessId);

				String hql = "from " + BaoxiaoItem.class.getName() + " where baoxiaoId =:bid";
				List<BaoxiaoItem> items = session.createQuery(hql).setString("bid", businessId).list();
				bx.setItems(items);

				return bx;
			} finally {
				session.close();
			}
		}
	}

	/**
	 * 保存报销单
	 * 
	 * @param bx
	 */
	@DataResolver
	public void saveBaoXiao(BaoXiao bx) {
		Session session = getSessionFactory().openSession();

		try {
			session.saveOrUpdate(bx);
			session.flush();

			Collection<BaoxiaoItem> items = bx.getItems();

			int moneyCount = 0;
			if (items != null && items.size() > 0) {
				for (BaoxiaoItem item : items) {
					item.setBaoxiaoId(bx.getId());
					session.saveOrUpdate(item);
					moneyCount += item.getMoney();
				}
			}

			StartProcessInfo info = new StartProcessInfo();
			info.setPromoter(ContextHolder.getLoginUserName());
			info.setBusinessId(bx.getId());
			info.setCompleteStartTask(true);

			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("moneyCount", moneyCount);
			variables.put("manager", "admin");
			variables.put("supermanager", "user1");
			info.setVariables(variables);

			propcessService.startProcessById(3211, info);
		} finally {
			session.flush();
			session.close();
		}
	}

	/**
	 * 完成审批任务
	 * 
	 * @param taskId
	 * @param opinion
	 */
	@Expose
	public void completeApprove(String taskId, String opinion) {
		TaskOpinion taskOpinion = new TaskOpinion(opinion);
		Long id = Long.valueOf(taskId);

		taskService.start(id);
		taskService.saveTaskAppointor(id, "user1", "复核人复核");
		taskService.complete(id, "复核", taskOpinion);
	}

	/**
	 * 完成任务
	 * 
	 * @param taskId
	 * @param opinion
	 */
	@Expose
	public void completeTask(String taskId, String opinion) {
		TaskOpinion taskOpinion = new TaskOpinion(opinion);
		taskService.start(Long.valueOf(taskId));
		taskService.complete(Long.valueOf(taskId), taskOpinion);
	}

	/**
	 * 根据taskId获得任务名称
	 * 
	 * @param taskId
	 * @return taskName
	 */
	@Expose
	public String getTaskName(String taskId) {
		Session session = getSessionFactory().openSession();
		Task task = (Task) session.get(Task.class, Long.valueOf(taskId));

		return task.getTaskName();
	}

	/**
	 * 查询待办任务
	 * 
	 * @return
	 */
	@DataProvider
	public Collection<Orderflow> loadTodo() {
		Session session = getSessionFactory().openSession();
		String username = ContextHolder.getLoginUser().getUsername();

		TaskQuery query = taskService.createTaskQuery();
		query.addAssignee(username);
		query.addTaskState(TaskState.Created);
		List<Task> tasks = query.list();

		Collection<Orderflow> orderflows = new ArrayList<Orderflow>();
		try {
			for (Task task : tasks) {
				Long taskId = task.getId();

				Criteria criteria = session.createCriteria(Orderflow.class);
				criteria.add(Restrictions.eq("taskId", taskId));
				
				List<Orderflow> list = criteria.list();
				Orderflow orderflow = new Orderflow();
				if (list.size() > 0){
					orderflow = list.get(0);
				}

				orderflows.add(orderflow);
			}
		} finally {
			session.close();
		}

		return orderflows;
	}

}
